package com.hzncc.flowable_diboot.service.impl;

import com.diboot.core.service.impl.BaseServiceImpl;
import com.diboot.core.vo.JsonResult;
import com.diboot.iam.util.IamSecurityUtils;
import com.hzncc.flowable_diboot.coderule.service.CodeRuleService;
import com.hzncc.flowable_diboot.entity.Clue;
import com.hzncc.flowable_diboot.entity.ClueFollow;
import com.hzncc.flowable_diboot.entity.ToDoList;
import com.hzncc.flowable_diboot.mapper.ClueFollowMapper;
import com.hzncc.flowable_diboot.service.ClueFollowService;
import com.hzncc.flowable_diboot.service.ClueService;
import com.hzncc.flowable_diboot.service.ToDoListService;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Objects;


/**
 * 线索跟进 相关Service实现类
 *
 * @author MyName
 * @version 1.0
 * @date 2024-06-06
 * Copyright © MyCorp
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ClueFollowServiceImpl extends BaseServiceImpl<ClueFollowMapper, ClueFollow> implements ClueFollowService {

    private final ClueService clueService;
    private final ToDoListService toDoListService;
    private final CodeRuleService codeRuleService;

    @Override
    public JsonResult<?> follow(ClueFollow clueFollow) {
        String clueId = clueFollow.getClueId();
        Clue clue = clueService.getEntity(clueId);
        // 已转化不能在跟进
        if (Objects.equals(clue.getStatus(), "used")) {
            return JsonResult.FAIL_EXCEPTION("已转化线索不能再次跟进!");
        }
        clueFollow.setFollower(IamSecurityUtils.getCurrentUserId());
        //clueFollow.setCode(codeRuleService.generateCode(ConstantUtil.CODE_RULE_CLUE_FOLLOW));
        // 生成待办
        if (clueFollow.getNextConnectTime() != null) {
            toDoListService.createToDo(new ToDoList().setModel(ConstantUtil.MODEL_SALES)
                    .setClueId(clueId)
                    .setExecutor(IamSecurityUtils.getCurrentUserId())
                    .setType(ConstantUtil.TODAY_CLUE)
                    .setDisTime(LocalDateTime.now())
                    .setMission(String.format(ConstantUtil.CLUE_FOLLOW_MSG_TEMPLATE, clue.getName()))
                    .setContactWay(clueFollow.getContactWay())
                    .setStartTime(clueFollow.getNextConnectTime()));
        }
        createEntity(clueFollow);
        return JsonResult.OK();
    }
}